<?php

namespace app\admin\controller;

use app\admin\logic\RoleLogic;
use app\common\exception\ApiErrDesc;
use think\App;
use think\facade\Validate;
use think\validate\ValidateRule;


/**
 * 角色
 * Class RoleController
 * @package app\admin\controller
 * @author ^2_3^王尔贝
 */
class RoleController extends EndController
{
    private $roleLogic;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->roleLogic = new RoleLogic();
    }

    /**
     * 编辑
     * @return \think\response\Json
     * @author ^2_3^王尔贝
     */
    public function edit()
    {
        $params = $this->request->post();
        //// 参数验证
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(),
            'r_name' => ValidateRule::isRequire(),
        ]);
        if( !$validate->check( $params ) ) {
            return retJson($validate->getError(), ApiErrDesc::ERR_VALIDATE[0]);
        }

        $flag = $this->roleLogic->save( $params );
        if( $flag !== false ) {
            return retJson('', 0, $flag);

        }else {
            return retJson('角色编辑失败，稍后再试', ApiErrDesc::ERR_UNKNOWN[0]);
        }
    }

    /**
     * 添加
     * @return \think\response\Json
     * @author ^2_3^王尔贝
     */
    public function add()
    {
        $params = $this->request->post();
        //// 参数验证
        $validate = Validate::rule([
            'r_name' => ValidateRule::isRequire(),
        ]);
        if( !$validate->check( $params ) ) {
            return retJson($validate->getError(), ApiErrDesc::ERR_VALIDATE[0]);
        }

        $flag = $this->roleLogic->save( $params );
        if( $flag !== false ) {
            return retJson('', 0, $flag);

        }else {
            return retJson('角色添加失败，稍后再试', ApiErrDesc::ERR_UNKNOWN[0]);
        }
    }

    /**
     * node节点
     * @return \think\response\Json
     * @author ^2_3^王尔贝
     */
    public function roleNodes()
    {
        $params = $this->request->post();
        $validate = Validate::rule([
            'role_id' => ValidateRule::isRequire(),
        ]);
        if( !$validate->check( $params ) ) {
            return retJson($validate->getError(), ApiErrDesc::ERR_VALIDATE[0]);
        }

        $roleNodes = $this->roleLogic->roleNodes($params);
        return retJson('', 0, $roleNodes);
    }

    /**
     * 有效角色
     * @return \think\response\Json
     * @author ^2_3^王尔贝
     */
    public function validRoles()
    {
        $params = $this->request->post();
        $list = $this->roleLogic->validRoles( $params );
        return retJson('', 0, $list);
    }

    /**
     * 分页数据
     * @return \think\response\Json
     * @author ^2_3^王尔贝
     */
    public function listPage()
    {
        $params = $this->request->post();
        $listPage = $this->roleLogic->listPage( $params );
        if( !empty( $listPage ) ) {
            $listPage = $this->transformPage( $listPage->toArray() );
        }
        return retJson('', 0, $listPage);
    }
}